package com.atguigu.spzx.service.user.service.impl;

import com.atguigu.spzx.common.handler.interceptor.SpzxAuthInterceptor;
import com.atguigu.spzx.service.user.mapper.UserAddressMapper;
import com.atguigu.spzx.service.user.service.RegionService;
import com.atguigu.spzx.service.user.service.UserAddressService;
import com.atguigu.spzx.model.entity.h5.UserAddress;
import com.atguigu.spzx.model.entity.region.Region;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * title:
 * author: zgl
 * date: 2024/1/18
 * description：
 */
@Service
public class UserAddressServiceImpl extends ServiceImpl<UserAddressMapper, UserAddress> implements UserAddressService {
    @Resource
    private RegionService regionService;

    @Override
    public List<UserAddress> findUserAddressList() {
        Long userId = SpzxAuthInterceptor.threadLocal.get().getId();
        List<UserAddress> list = this.list(Wrappers.lambdaQuery(UserAddress.class).eq(UserAddress::getUserId, userId));
        return list;
    }

    @Override
    public void deleteById(Long id) {
        this.removeById(id);
    }

    @Override
    public void updateAddress(UserAddress userAddress) {
        UserAddress fullUserAddress = getFullAddress(userAddress);
        this.updateById(fullUserAddress);
    }

    @Override
    public void addAddress(UserAddress userAddress) {
        UserAddress fullUserAddress = getFullAddress(userAddress);
        this.save(fullUserAddress);
    }


    private UserAddress getFullAddress(UserAddress userAddress) {
        Long userId = SpzxAuthInterceptor.threadLocal.get().getId();
        if (userAddress.getIsDefault() == 1) {
            UserAddress defaultAddress = this.getOne(Wrappers.lambdaQuery(UserAddress.class).eq(UserAddress::getIsDefault, 1).eq(UserAddress::getUserId, userId));
            if (defaultAddress != null) {
                defaultAddress.setIsDefault(0);
                this.updateById(defaultAddress);
            }
        }
        Region r1 = regionService.findByCode(userAddress.getProvinceCode());
        Region r2 = regionService.findByCode(userAddress.getCityCode());
        Region r3 = regionService.findByCode(userAddress.getDistrictCode());
        userAddress.setFullAddress(r1.getName() + r2.getName() + r3.getName());
        userAddress.setUserId(userId);
        return userAddress;
    }
}
